//
//  ShoppingCartViewController.m
//  firstpoint
//
//  Created by 泽中 on 2017/7/5.
//  Copyright © 2017年 xzcysoft. All rights reserved.
//

#import "ShoppingCartViewController.h"
#import "ShoppingCartTableViewCell.h"
#import "ShoppingCartModel.h"
#import "CommodityDetailsViewController.h"
@interface ShoppingCartViewController ()<UITableViewDelegate,UITableViewDataSource>
{
    UITableView*tabView;
    NSMutableArray*dataArr;
    NSDictionary*dataDic;
    NSArray*shopDataArr;
    
    NSInteger yuanbaoZongJia;
    NSInteger jinbiZongjia;
    NSInteger goumaiCount;
    UILabel*yuanbaoLab;
    UILabel*jinbiLab;
    
    NSString*shangpinId;
    
    
    float allPrice;
    NSMutableArray *infoArr;
    
}


@end

@implementation ShoppingCartViewController
-(void)httpRequest
{
    //初始化数据
    allPrice = 0.0;
    infoArr = [[NSMutableArray alloc]init];
    dataArr = [NSMutableArray new];
    NSString*tokenStr= OBJECT_FOR_KEY(@"token");
    NSString*urlStr=[NSString stringWithFormat:@"/shoppingCart/index.api?access_token=%@",tokenStr];
    [HTTPURL postRequest:LINK_BASE_URL(urlStr) parameters:@{@"userId":userid,@"pageIndex":@"0"} success:^(NSURLSessionDataTask *task, id responseObject) {
        NSLog(@"%@",responseObject);
        dataDic=[PublicTools dictionaryWithJsonString:responseObject[@"data"]];
        dataArr=dataDic[@"rows"];
        for (int i = 0; i<dataArr.count; i++)
        {
            //封装数据模型
            ShoppingCartModel *goodsModel = [[ShoppingCartModel alloc]initWithDict:dataArr[i]];
            
            //将数据模型放入数组中
            [infoArr addObject:goodsModel];
             allPrice = 0.0;
            jinbiLab.text = [NSString stringWithFormat:@"%.2f",allPrice];
        }
        [tabView reloadData];
  } filure:^(NSURLSessionDataTask *task, id error) {
      
  }];

}
-(void)deleteRequest :(UIButton *)button
{
    NSString*tokenStr= OBJECT_FOR_KEY(@"token");
    NSString*urlStr=[NSString stringWithFormat:@"/shoppingCart/deleteShoppingCart.api?access_token=%@",tokenStr];
    [HTTPURL postRequest:LINK_BASE_URL(urlStr) parameters:@{@"userId":userid,@"shoppingId":shangpinId} success:^(NSURLSessionDataTask *task, id responseObject) {
        NSLog(@"%@",responseObject);
//        if ([responseObject[@"retFlag"]integerValue]==1) {
//             [infoArr removeObjectAtIndex:button.tag-1];
//            [tabView reloadData];
//            [self totalPrice];
//        }
       
      
        [self httpRequest];
    } filure:^(NSURLSessionDataTask *task, id error) {
        
    }];

}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.title=@"购物车";
    self.view.backgroundColor=LRRGBColor(235, 240, 243);
    
    [self setUI];
    [self setDiView];
    [self httpRequest];
    
//    for (int i=0; i<15; i++) {
//        ShoppingCartModel*model = [ShoppingCartModel new];
//        model.title = @"ss";
//        [dataArr addObject:model];
//    }
}
-(void)setUI
{
   
    tabView=[[UITableView alloc]initWithFrame:CGRectMake(0, 64, width_screen, height_screen-64-50) style:1];
    tabView.separatorStyle=0;
    tabView.delegate=self;
    //    tabView.mj_header
    tabView.dataSource=self;
    [tabView registerClass:[ShoppingCartTableViewCell class] forCellReuseIdentifier:@"cell"];
    [self.view addSubview:tabView];
   
}
-(void)setDiView
{
    //底部view
    UIView*view=[[UIView alloc]initWithFrame:CGRectMake(0, height_screen-50, width_screen, 50)];
    view.backgroundColor=[UIColor whiteColor];
    [self.view addSubview:view];
    //全选
    UIButton*quanxuanBtn=[UIButton buttonWithType:UIButtonTypeCustom];
    quanxuanBtn.frame=CGRectMake(15, 15, 20, 20);
    quanxuanBtn.imageView.contentMode = UIViewContentModeScaleAspectFit;

    [quanxuanBtn setImage:[UIImage imageNamed:@"weixuanzhong"] forState:0];
    [quanxuanBtn setImage:[UIImage imageNamed:@"xuanzhong"] forState:UIControlStateSelected];
    [quanxuanBtn addTarget:self action:@selector(quqnxuanButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    [quanxuanBtn setTitleColor:[UIColor lightGrayColor] forState:0];
        [view addSubview:quanxuanBtn];
    UILabel*quanxuanLab=[[UILabel alloc]initWithFrame:CGRectMake(40, 15, 28, 20)];
    quanxuanLab.text=@"全选";
    quanxuanLab.textColor=[UIColor lightGrayColor];
    quanxuanLab.font=[UIFont systemFontOfSize:13];
    [view addSubview:quanxuanLab];
    //合计
    UILabel*hejiLab=[[UILabel alloc]initWithFrame:CGRectMake(80, 15, 42, 20)];
    hejiLab.text=@"合计";
    [view addSubview:hejiLab];
    
//    //元宝
//   yuanbaoLab=[[UILabel alloc]initWithFrame:CGRectMake(127, 10, 100, 13)];
//    yuanbaoLab.text=@"0元宝";
//    yuanbaoLab.font=[UIFont systemFontOfSize:13];
//    yuanbaoLab.textColor=LRRGBColor(215, 25, 36);
//    [view addSubview:yuanbaoLab];
    //金币
    jinbiLab=[[UILabel alloc]initWithFrame:CGRectMake(127, 10, 100, 20)];
    jinbiLab.textColor=LRRGBColor(215, 25, 36);
    jinbiLab.text=@"0金币";
    jinbiLab.font=[UIFont systemFontOfSize:18];

    [view addSubview:jinbiLab];
    //结算button
    UIButton*jiesuanButton=[UIButton buttonWithType:UIButtonTypeCustom];
    jiesuanButton.backgroundColor=LRRGBColor(215, 25, 36);
    jiesuanButton.frame=CGRectMake(width_screen-118, 0, 118, 50);
    [jiesuanButton addTarget:self action:@selector(jiesuanbtnClcike) forControlEvents:UIControlEventTouchUpInside];
    [jiesuanButton setTitle:@"结算" forState:0];
    [view addSubview:jiesuanButton];
    
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 100;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return dataArr.count;
    
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    ShoppingCartTableViewCell *cell =[tableView dequeueReusableCellWithIdentifier:@"cell"];
    
    [cell.seletedButton addTarget:self action:@selector(danxuanButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    cell.seletedButton.tag=indexPath.row+10000;
    ShoppingCartModel *mode = infoArr[indexPath.row];
    if (mode.isSelected)
    {
        [cell.seletedButton setImage:[UIImage imageNamed:@"xuanzhong"] forState:0];
    }else{
        [cell.seletedButton setImage:[UIImage imageNamed:@"weixuanzhong"] forState:0];
    }
    cell.titleLab.text=mode.title;
    cell.yuanbaoLab.text=[NSString stringWithFormat:@"%@金币",mode.goodsPrice];
    cell.numLab.text=[NSString stringWithFormat:@"x %d",mode.goodsNum];
    [cell.deleteButton addTarget:self action:@selector(deleteClick:) forControlEvents:UIControlEventTouchUpInside];
    cell.deleteButton.tag=indexPath.row+1;
//    ShoppingCartModel*model = dataArr[indexPath.row];
//    cell.seletedButton.selected =model.isSelected;
    return cell;
}
-(void)deleteClick:(UIButton*)btn
{
    shangpinId= [NSString stringWithFormat:@"%@",dataArr[btn.tag-1][@"id"]];
    [self deleteRequest:btn];
    
   
//
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
//    /**
//     *  判断当期是否为选中状态，如果选中状态点击则更改成未选中，如果未选中点击则更改成选中状态
//     */
//    ShoppingCartModel *model = infoArr[indexPath.row];
//    
//    if (model.isSelected)
//    {
//        model.isSelected = NO;
//    }
//    else
//    {
//        model.isSelected = YES;
//    }
//    
//    //刷新整个表格
//    //    [_MyTableView reloadData];
//    
//    //刷新当前行
//    [tabView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
//    
//    [self totalPrice];
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    CommodityDetailsViewController*vc=[CommodityDetailsViewController new];
    if (dataArr.count>indexPath.row) {
        NSString*idStr=[NSString stringWithFormat:@"%@",dataArr[indexPath.row][@"goodId"]] ;
        vc.ID=idStr;
    }
    
//    vc.hidesBottomBarWhenPushed=YES;
    [self.navigationController pushViewController:vc animated:YES];
}
#pragma mark -- 计算价格
-(void)totalPrice
{
    //遍历整个数据源，然后判断如果是选中的商品，就计算价格（单价 * 商品数量）
    for ( int i =0; i<infoArr.count; i++)
    {
        ShoppingCartModel *model = [infoArr objectAtIndex:i];
        if (model.isSelected)
        {
            allPrice = allPrice + model.goodsNum *[model.goodsPrice intValue];
        }
    }
    
    //给总价文本赋值
    jinbiLab.text = [NSString stringWithFormat:@"%.2f",allPrice];
    NSLog(@"%f",allPrice);
    
    //每次算完要重置为0，因为每次的都是全部循环算一遍
    allPrice = 0.0;
}
-(void)danxuanButtonClick:(UIButton*)btn
{
    /**
     *  判断当期是否为选中状态，如果选中状态点击则更改成未选中，如果未选中点击则更改成选中状态
     */
    ShoppingCartModel *model = infoArr[btn.tag-10000];
    
    if (model.isSelected)
    {
        model.isSelected = NO;
    }
    else
    {
        model.isSelected = YES;
    }
    
    //刷新整个表格
    //    [_MyTableView reloadData];
    
    //刷新当前行
//    NSIndexPath *ind = (NSIndexPath *)(btn.tag-10000);
//    [tabView reloadRowsAtIndexPaths:@[btn.tag-10000] withRowAnimation:UITableViewRowAnimationAutomatic];
    [tabView reloadData];
    [self totalPrice];
}
//全选
-(void)quqnxuanButtonClick:(UIButton*)sender
{
    //判断是否选中，是改成否，否改成是，改变图片状态
    sender.tag = !sender.tag;
    if (sender.tag)
    {
        [sender setImage:[UIImage imageNamed:@"xuanzhong"] forState:UIControlStateNormal];
        
    }else{
        [sender setImage:[UIImage imageNamed:@"weixuanzhong"] forState:UIControlStateNormal];
    }
    //改变单元格选中状态
    for (int i=0; i<infoArr.count; i++)
    {
        ShoppingCartModel *model = [infoArr objectAtIndex:i];
        model.isSelected = sender.tag;
    }
    //计算价格
    [self totalPrice];
    //刷新表格
    [tabView reloadData];
}
//结算
-(void)jiesuanbtnClcike{
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
